/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Dimensions,
  WebView,
  TouchableOpacity,
  Alert,
  ScrollView,
  RefreshControl,
  AsyncStorage,
} from 'react-native';


import Icon from 'react-native-vector-icons/FontAwesome';

import DropdownAlert from 'react-native-dropdownalert'

var Header = require("./Header");

var net = require("./../net/NetUitl");

var TEXT_INPUT_REF = 'urlInput';
var WEBVIEW_REF = 'webview';
var DEFAULT_URL = 'http://www.lcode.org';
var BGWASH = 'rgba(255,255,255,0.2)';


var _navigator;
var Webpage;

var user_id;
class Web extends Component {
	constructor(props) {  
		super(props);
		_navigator = this.props.navigator;
		DEFAULT_URL = this.props.url;
		
		this._collect = this._collect.bind(this);
		
		this.state={color:"#eeeeee",isRefreshing:false,collect:false};
		
		
		this._netCallBack = this._netCallBack.bind(this);
		this._errorCallBack = this._errorCallBack.bind(this);
		this.requireUrl = this.requireUrl.bind(this);
		this._collectCallBack = this._collectCallBack.bind(this);
  	}
	
	componentDidMount() {
		_this = this;
		
		
		AsyncStorage.getItem("user_id",function(errors,result){
			
			if(result != null){
				user_id = result;
				_this.requireUrl();
			}
		});
	}
	
	componentWillUnmount(){
		if(this.props.refresh != null){
			this.props.refresh();
		}
	}
	
	requireUrl(){
		let formData = new FormData();  
		formData.append("user_id",user_id);  
		formData.append("art_id",this.props.articleid);
		var fetchOptions = {
			method: 'POST',
			headers: { 
			    'Accept': 'application/json',
			},
			body: formData
		}; 
		        
		net.postFrom("http://www.idolly.com/article/index/check"
			,fetchOptions
			,this._netCallBack
			,this._errorCallBack);
	}
	
	async _netCallBack(data){
		if(data.code === "0"){
			this.setState({collect:false});
		}else{
			this.setState({collect:true});
		}
		
//		if(this.state.collect){
//			this.setState({
//				color: "#ff0000",
//			});
//		}else{
//			this.setState({
//				color: "#eeeeee",
//			});
//		}
	}
	
	_collectCallBack(data){
		if(data.code === "1"){
			this.setState({collect:!this.state.collect});
			if(this.state.collect){
				this.dropdown.alertWithType('info', '提示', '文章已经收藏，请在我的（我的收藏）里面查看');
			}
		}
	}
	
	_errorCallBack(){

	}
	
	onClose(data) {
	  // data = {type, title, message}
	}
		
	_collect(){
		if(this.state.collect){
			let formData = new FormData();  
			formData.append("user_id",user_id);  
			formData.append("art_id",this.props.articleid);
			var fetchOptions = {
	          	method: 'POST',
	          	headers: { 
	          		'Accept': 'application/json',
	          	},
	          	body: formData
	       	}; 
        
			net.postFrom("http://www.idolly.com/article/index/cancelCollect"
				,fetchOptions
				,this._collectCallBack
				,this._errorCallBack);
		}else{
			let formData = new FormData();  
			formData.append("user_id",user_id);  
			formData.append("art_id",this.props.articleid);
			var fetchOptions = {
	          	method: 'POST',
	          	headers: { 
	          		'Accept': 'application/json',
	          	},
	          	body: formData
	       	}; 
        
			net.postFrom("http://www.idolly.com/article/index/Collect"
				,fetchOptions
				,this._collectCallBack
				,this._errorCallBack);
		}
	}

	_onRefresh(){
//		this.setState({isRefreshing:true});
//		net.postJson("http://www.idolly.com/article/index/articleBySort"
//			,null
//			,this._netCallBack
//			,this._errorCallBack);
//		setTimeout(() => {
//	      	this.setState({isRefreshing:false});
//	    }, 1000);
	}
	
  	render() {
  		
  		let starcolor = this.state.collect?"#ff0000":"#eeeeee";
//		if(this.state.collect){
//				this.setState({
//					color: "#ff0000",
//				});
//				Alert.alert("收藏成功,请在个人设置中查看");
//			}else{
//				this.setState({
//					color: "#eeeeee",
//				});
//			}
    	return (
    		<View style={styles.container}>
	      		<Header name="文章" IconLeft="chevron-left" onPressLeft={()=>_navigator.pop()}
	      				IconRight="star" IconRightColor={starcolor} onPressRight={()=>this._collect()}/>
	      		<View style={styles.contain}>
		      		<WebView
			          	ref={WEBVIEW_REF}
			          	automaticallyAdjustContentInsets={false}
			          	style={styles.webView}
			          	source={{uri: DEFAULT_URL}}
			          	javaScriptEnabled={true}
			          	domStorageEnabled={true}
			          	decelerationRate="normal"
			          	onNavigationStateChange={this.onNavigationStateChange}
			          	onShouldStartLoadWithRequest={this.onShouldStartLoadWithRequest}
			          	startInLoadingState={true}
			          	scalesPageToFit={true}
			        />
	      		</View>
	      		<View style={styles.bottom}>
			      	<TouchableOpacity style={{marginLeft:40}} onPress={()=> this.refs[WEBVIEW_REF].goBack()}>
						<View style={styles.title} style={styles.icon_left}>
							<Icon name="chevron-left" size={18} color="#EEEEEE" />
						</View>
					</TouchableOpacity>
					<TouchableOpacity style={{marginLeft:30}} onPress={()=> this.refs[WEBVIEW_REF].goForward()}>
						<View style={styles.title} style={styles.icon_left}>
							<Icon name="chevron-right" size={18} color="#EEEEEE" />
						</View>
					</TouchableOpacity>
					<View style={{flex:1}}></View>
					<View style={{width:50}}>
						<TouchableOpacity onPress={() => this.refs[WEBVIEW_REF].reload()}>
							<View  style={styles.icon_left}>
								<Icon name="refresh" size={18} color="#EEEEEE" />
							</View>
						</TouchableOpacity>
					</View>
	      		</View>
	      		<DropdownAlert ref={(ref) => this.dropdown = ref} onClose={(data) => this.onClose(data)} />
      		</View>
    	);
  	}
}

const styles = StyleSheet.create({
	container: {
	    flex: 1,
	    justifyContent: 'center',
	    alignItems: 'center',
	    backgroundColor: '#FAF4FF',
	},
	contain: {
	    flex: 1,
	    backgroundColor: '#FAF4FF',
	},
  	bottom:{
  		flexDirection:'row',
  		alignItems: 'center',
  		height:50,
  		width:Dimensions.get('window').width,
  		backgroundColor: '#6c1ddc',
  	},
  	webView:{  
        backgroundColor:'#000000',   
        width:Dimensions.get('window').width,
        flex:1,
        height:Dimensions.get('window').height,
    },
    scrollview: {  
	    flex: 1,  
	   	width:Dimensions.get('window').width,
	},
});

module.exports = Web;
